// 单例模式的目的是限制一个类只能被实例化一次，提供一个全局的访问点。
// 单例模式又被分为懒汉单例模式和饿汉单例模式，
// 懒汉单例模式就是在第一次调用时实例化，
// 饿汉单例模式是类加载时就实例化。

// 懒汉单例模式
class PeopleSingle {
  /**核心 - 一个接收实例的静态成员 */
  private static people: PeopleSingle;
  public name: string;

  /**核心 - 私有构造函数 */
  // private constructor(name: string) {
  //   this.name = name;
  // }

  /**核心 - 获取实例 */
  public static getInstance(name): PeopleSingle {
    if (this.people == null) {
      this.people = new PeopleSingle();
    }
    return PeopleSingle.people;
  }

}

let people = PeopleSingle.getInstance('金晒晒');
console.log(people.name);
let people2 = PeopleSingle.getInstance('金晒晒');
console.log(people === people2);

people.name = 'test';
console.log(people.name);
console.log(people2.name)

// 饿汉单例模式
class HungryPeopleSingle {
  /**核心 - 一个接收实例的静态成员，直接创建好实例 */
  private static people: HungryPeopleSingle = new HungryPeopleSingle();
  public name: string;

  // /**核心 - 私有构造函数 */
  // private constructor(name: string) {
  //   this.name = name;
  // }

  /**核心 - 获取实例 */
  public static getInstance(): HungryPeopleSingle {
    return HungryPeopleSingle.people;
  }
}

let hungry_single12 = HungryPeopleSingle.getInstance()
console.log(hungry_single12.name)

// 输出 true
let hungry_single123 = HungryPeopleSingle.getInstance()
console.log(hungry_single12 === hungry_single123)

hungry_single12.name = 'test'
console.log(hungry_single12.name)
console.log(hungry_single123.name)

